package com.yanwq.sayhi.rest;

import com.yanwq.sayhi.bean.User;
import com.yanwq.sayhi.exception.ExResponse;
import com.yanwq.sayhi.service.UserService;
import com.yanwq.sayhi.tool.JSONResultTool;
import com.yanwq.sayhi.tool.MD5Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.UUID;

/**
 * 作者：yanweiqiang。
 * 日期：2016/1/28。
 */
@RestController
@RequestMapping(path = "/user")
public class UserRest extends BaseRest {

    @Autowired
    private UserService userService;

    @RequestMapping(path = "/test", method = RequestMethod.GET)
    public String test() throws SQLException {
        return "Hello world!";
    }

    @RequestMapping(path = "/register", method = RequestMethod.POST)
    public User register(@RequestBody User user) {
        user.setUuid(UUID.randomUUID().toString());
        user.setPassword(MD5Tool.GetMD5Code(user.getPassword()));
        user.setRegisterTime(System.currentTimeMillis());
        user.setToken(UUID.randomUUID().toString());
        return userService.save(user);
    }

    @RequestMapping(path = "/login", method = RequestMethod.GET)
    public User login(@RequestParam String username, @RequestParam String password) {
        User result = userService.findByUsernameAndPassword(username, MD5Tool.GetMD5Code(password));

        if (result == null) {
            throw new ExResponse(1001, "用户名或密码错误");
        }

        return result;
    }

    @RequestMapping(path = "/update", method = RequestMethod.POST)
    public User update(@RequestBody User user) {
        return userService.save(user);
    }

    @RequestMapping(path = "/find/uuid/{uuid}", method = RequestMethod.GET)
    public User findByUuid(@PathVariable String uuid) {
        return userService.findByUuid(uuid);
    }

    @RequestMapping(path = "/username", method = RequestMethod.GET)
    public String hasUsername(@RequestParam String username) {
        return JSONResultTool.makeJSONResult(userService.hasUsername(username));
    }

    @RequestMapping(path = "/phone", method = RequestMethod.GET)
    public String hasPhone(@RequestParam String phone) {
        return JSONResultTool.makeJSONResult(userService.hasPhone(phone));
    }

    @RequestMapping(path = "/nickname", method = RequestMethod.GET)
    public String hasNickname(@RequestParam String nickname) {
        return JSONResultTool.makeJSONResult(userService.hasNickname(nickname));
    }
}
